<template>
  <div class="common-layout" style="margin: 100px 100px">
    <el-container>
      <el-aside width="400px">
        <div class="checkbox-container">
           <el-aside width="200px">
            角色
            <!-- 使用 el-tree 组件展示树形数据 -->
            <el-tree :data="RoleModel" :highlight-current="true" ref="treeRef" :props="treePropsRole" node-key="roleId"
              @node-click="handleNodeClickRole">
            </el-tree>
         
          </el-aside>
    
        </div>
      </el-aside>
       <el-aside width="200px">
            <div >
              菜单
              <!-- 使用 el-tree 组件 -->
              <el-tree :data="data" :default-checked-keys="AddModel.menuId" show-checkbox node-key="menuId"
                :props="defaultProps" @check-change="handleCheckChange" ref="treeRef"
                :default-expand-all="true"></el-tree>
            
            </div>
          </el-aside>

  
    </el-container>
   <el-form>
     <el-form-item >
      <template v-slot="scoped">
       <el-button type="primary" @click="submitForm()">提交</el-button>
       </template>
     </el-form-item>
   </el-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref,nextTick } from "vue";
import {
  ElMessage,
  type ComponentSize,
  type FormInstance,
  type FormRules,
} from "element-plus";
import axios from "axios";
import { useRouter } from "vue-router";
import { useCounterStore } from "@/stores/counter";
import { ElTree } from 'element-plus';
const store = useCounterStore();
const router = useRouter();

onMounted(() => {
  GetRole();
  getMenuIndex();
});
/* const roles = ref();
const page = ref({
  totalCount: 0,
  totalPage: 0,
  PageIndex: 1,
  PageSize: 15,
});
 */
//获取角色的数据
const RoleModel = ref([])

//获取角色数据(id, 名称)
const GetRole = () => {
  axios.get("https://localhost:7174/api/Message/GetRole/GetRole").then(res => {
    console.log(res.data.data, "角色数据")
    RoleModel.value = res.data.data
    console.log(RoleModel.value, "角色名称")
  })
}

// 定义树的属性配置
const treePropsRole: any = ref({
  label: 'roleName', // 指定节点的标签显示字段为 roleName
  children: [] // 指定子节点字段为 children
});
/* const getRole = () => {
  axios
    .get("https://localhost:7174/api/Message/GetRole", { params: page.value })
    .then((res) => {
      if (res.data.code == 200) {
        roles.value = res.data.data;
      }
    });
}; */

const defaultProps = {
  children: "children",
  label: "menuName",
  value: "menuId",
};
const data = ref([]);
const treeData = ref([]);
// 将扁平数据转换为树形数据
const getMenuIndex = () => {
  axios
    .get("https://localhost:7174/api/Message/GetChildrenMenus/ChildrenMenus")
    .then((res) => {
      data.value = res.data.data;
   treeData.value = convertToTree(data.value)
      //  console.log(res.data.data[0].children);
    });
};


const treeRef = ref();


const AddModel = reactive({
  roleId: 0,
  menuId: [],
})
// 处理节点点击事件(点击角色，获取对应的菜单)
const handleNodeClickRole = (data: any) => {
  //清空节点
  AddModel.menuId = [];
  AddModel.roleId = data.roleId;
  axios.get(`https://localhost:7174/api/Message/GetRoleMenu/GetRoleMenu?RoleId=${data.roleId}`).then(res => {
    AddModel.menuId = res.data.data.map((item: any) => item.menuId)
  
    nextTick() // 等待 DOM 更新完成
    // 更新 el-tree 的选中状态
    treeRef.value.setCheckedKeys(AddModel.menuId);
  })
};

// 将菜单数据转换为树形结构
const convertToTree= (data: any) => {
  const tree: any = [];
  const map: any = {};

  // 先将每个节点存储到 map 中
  data.forEach((item: any) => {
    map[item.menuId] = { ...item, children: [] };
  });

  // 再根据 parentId 构建树形结构
  data.forEach((item: any) => {
    if (item.parentId === 0) {
      tree.push(map[item.menuId]);
    } else {
      const parent = map[item.parentId];
      if (parent) {
        parent.children.push(map[item.menuId]);
      }
    }
  });
  return tree;
}

//获取菜单多选值
const handleCheckChange = () => {
  AddModel.menuId = treeRef.value?.getCheckedKeys() || [];
  // console.log(AddModel.menuId, '获取单个选中值')
};


//批量添加菜单
const submitForm = () => {

// console.log(getrolebyMenus.roleId, "getrolebyMenus.rolId");

  axios.post("https://localhost:7272/api/Message/CreateRoleMenu", AddModel)
    .then((res) => {
    console.log(res.data);
    if (res.data.code == 100) {
      ElMessage.success("分配成功");
      return;
    }
    else {
      ElMessage.error("分配失败");
      return;
    }
  })
};
</script>

<style scoped>
.checkbox-container {
  margin-bottom: 8px;
}
</style>